/* linghuam 封装播放控件 依赖 [playback,jquery,leaflet1.0.0]
* 示例
   new L.ICT.Control.PlayBack (data,null,null,options).show(map);
*/

define("control/playback", [
    "leaflet",
    "jquery",
    "leafletPlayback",
    "plugins/rangeSlider"

], function (L) {

    L.ICT.Control = L.ICT.Control || {};

    L.ICT.Control.PlayBack = L.Class.extend({


        options: {
            position: 'topright', //控件摆放位置
            data: {},
            speed: 13,
            maxSpeed: 65,
            trackPointOptions: {
                isDraw: true,
                opacity:0.8
            },
            trackLineOptions: {
                isDraw: true,
                color:'#ef0300'
            }
        },

        templateHtml: '<div class="playback-operation">' +
            '<ul>'
            // +'<li class="item item-stop" data-info="1" title="停止"><img src="themes/images/stateplayback/ico_stop.png"></li>'
            +
            '<li class="item item-start play" data-info="2" title="播放"><img src="themes/images/stateplayback/ico_play.png"></li>' +
            '<li class="item item-restart" data-info="3" title="重播"><img src="themes/images/stateplayback/ico_restart.png"></li>' +
            '<li class="item item-slow" data-info="4" title="减速"><img src="themes/images/stateplayback/ico_pre.png"></li>' +
            '<li class="item item-quick" data-info="5" title="加速"><img src="themes/images/stateplayback/ico_next.png"></li>' +
            '<li class="item item-speed"><span>X1</span></li>' +
            '<li class="item item-close" data-info="6" title="关闭"><img src="themes/images/stateplayback/ico_close.png"></li>' +
            '</ul>' +
            '</div>' +
            '<div class="playback-scrollbar">' +
            '<ul>' +
            '<li class="item item-time"><span class="startTime"></span><span class="endTime"></span></li>' +
            '<li class="item item-scroll"><input type="range" class="range"></li>' +
            '<li class="item item-curtime"><span class="curTime"></span></li>' +
            '</ul>' +
            '</div>',

        /*
         *@map obj 
         *@data Array objArr
         *@clockCallback Function 时钟变化时触发回调
         *@closeCallback Function 关闭控件时触发回调
         *@options obj 
         */
        initialize: function (data, clockCallback, closeCallback, options) {
            L.setOptions(this, options);
            this._data = data;
            this._closeCallback = closeCallback;
            this._playback = {};
        },

        //显示控件
        show: function (map) {
            if(!map) {
                return;
            }
            this._map = map;
            this.onAdd(map);
            return this;
        },

        //关闭控件
        close: function () {
            L.DomUtil.remove(this._container);
            if(this.onRemove) {
                this.onRemove(this._map);
            }
            return this;
        },

        //添加
        onAdd: function (map) {
            this._map = map;
            this._initUi();
            this._initStyle();

            var datas = this.dataTransform(this._data);
            if(map && datas) {
                var tracks = [];
                for(var i = 0, len = datas.length; i < len; i++) {
                    var track = new L.PlayBack.Track(datas[i], this.options);
                    tracks.push(track);
                }
                this._playback.draw = new L.PlayBack.Draw(map, this.options);
                this._playback.trackController = new L.PlayBack.TrackController(tracks, this._playback.draw, map, this.options);
                this._playback.clock = new L.PlayBack.Clock(this._playback.trackController, this._clockCallback.bind(this), this.options);

                this._playback.clock.setCursor(this.getStartTime())
                this._initEvts();
                this._setTime();

                //处理只有一个点情况
                if(this.getStartTime() === this.getEndTime()) {
                    L.ict.app.util.dialog.alert("提示", "只有一个历史轨迹点，无法进行回放！");
                }
            }
            return this._container;
        },

        //移除
        onRemove: function () {
            this._playback.draw.removeLayer()
            if(typeof this._closeCallback === "function") {
                this._closeCallback.call(this, this);
            }
        },

        _initUi: function () {
            var playbackName = 'ict-control-playback',
                container = this._container = L.DomUtil.create('div', playbackName),
                options = this.options;
            // L.DomEvent.disableClickPropagation(container);  //不能禁用事件冒泡，否则不能拖动
            container.innerHTML = this.templateHtml;
            $("body").append($(container));
            //拖动
            var pid = "ict-control-playback" + L.stamp({});
            var cid = "playback-operation" + L.stamp({});
            $(container).attr("id", pid);
            $(container).find(".playback-operation").attr("id", cid)
            L.ict.app.util.tool.drag(pid, cid);
            //速度
            $(container).find(".playback-operation .item-speed span").text("X" + this.options.speed);
        },

        _initStyle: function () {
            var $container = $(this._container);
            $container.find(".item-start").attr("title", "播放");
            $container.find(".item-restart").attr("title", "重新播放");
            $container.find(".item-slow").attr("title", "减速播放");
            $container.find(".item-quick").attr("title", "加速播放");
            $container.find(".item-close").attr("title", "关闭");
        },

        _initEvts: function () { //jquery
            var self = this,
                btns = $(self._container).find('.playback-operation>ul>li'),
                range = $(self._container).find('.playback-scrollbar input')[0];

            btns.each(function () {
                L.DomEvent
                    .on(this, 'mousedown dbclick', L.DomEvent.stopPropagation)
                    .on(this, 'click', L.DomEvent.stop)
                    .on(this, 'click', self._btnClick, self);
            });

            range.min = self.getStartTime();
            range.max = self.getEndTime();
            range.value = self.getTime();
            L.DomEvent
                .on(range, 'click mousedown dbclick', L.DomEvent.stopPropagation)
                .on(range, 'click', L.DomEvent.preventDefault)
                .on(range, 'change', self._onRangeChange, self)
                .on(range, 'mousemove', self._onRangeChange, self);
        },

        _btnClick: function (e) {
            var $this = $(e.currentTarget);
            var type = $(e.currentTarget).data("info");
            switch(type) {
            case 1:
                ;
                break;
            case 2:
                if($this.hasClass("play")) {
                    $this.removeClass("play");
                    $this.find("img").attr("src", "themes/images/stateplayback/ico_push.png");
                    $this.attr("title", "暂停");
                    this.start();
                } else {
                    $this.addClass("play");
                    $this.find("img").attr("src", "themes/images/stateplayback/ico_play.png");
                    $this.attr("title", "播放");
                    this.stop();
                }
                break;
            case 3:
                $this.siblings(".item-start").removeClass("play");
                $this.siblings(".item-start").find("img").attr("src", "themes/images/stateplayback/ico_push.png");
                $this.siblings(".item-start").attr("title", "暂停");
                this.rePlaying();
                break;
            case 4:
                this.slowSpeed();
                break;
            case 5:
                this.quickSpeed();
                break;
            case 6:
                this.close();
                break;
            default:
                ;
            }

        },

        _onRangeChange: function (e) {
            var val = Number(e.target.value);
            this._playback.clock.setCursor(val);
        },

        _clockCallback: function (s) {
            var $container = $(this._container);
            var range = $container.find('.playback-scrollbar input')[0];

            // 更新时间
            var time = L.PlayBack.Util.getTimeStrFromUnix(s, 's')
            $container.find(".playback-scrollbar .curTime").text(time);

            // 更新时间轴
            range.value = s;
            //给滑动块添加颜色
            var percent = parseInt((s - range.min) / (range.max - range.min) * 100);
            $(range).css('background-size', percent + '% 100%');

            // 播放结束后改变播放按钮样式
            if(s >= this.getEndTime()) {
                var $playbtn = $container.find('.playback-operation>ul>li.item-start');
                $playbtn.addClass("play");
                $playbtn.find("img").attr("src", "themes/images/stateplayback/ico_play.png");
                $playbtn.attr("title", "播放");
                this._playback.clock.stop();
            }
        },

        _setTime: function () {
            var $container = $(this._container),
                startTime = L.ict.app.util.dateTime.formatDateFULL(new Date(this.getStartTime() * 1000)),
                endTime = L.ict.app.util.dateTime.formatDateFULL(new Date(this.getEndTime() * 1000)),
                curTime = L.ict.app.util.dateTime.formatDateFULL(new Date(this.getTime() * 1000));
            $container.find(".playback-scrollbar .startTime").text(startTime);
            $container.find(".playback-scrollbar .endTime").text(endTime);
            $container.find(".playback-scrollbar .curTime").text(curTime);
        },

        //开始播放
        start: function () {
            this._playback.clock.start();
        },

        //停止播放
        stop: function () {
            this._playback.clock.stop();
        },

        //加速播放
        quickSpeed: function () {
            this._playback.clock.quickSpeed()
            var sp = this._playback.clock.getSpeed()
            $(this._container).find(".playback-operation .item-speed span").text("X" + sp);
        },

        //减速播放
        slowSpeed: function () {
            this._playback.clock.slowSpeed()
            var sp = this._playback.clock.getSpeed()
            $(this._container).find(".playback-operation .item-speed span").text("X" + sp);
        },

        //重新播放
        rePlaying: function () {
            this._playback.clock.rePlaying()
        },

        //获取当前时间
        getTime: function () {
            return this._playback.clock.getCurTime()
        },

        //获取开始时间  
        getStartTime: function () {
            return this._playback.clock.getStartTime()
        },

        //获取结束时间
        getEndTime: function () {
            return this._playback.clock.getEndTime()
        },

        //数据格式转换
        dataTransform: function (data) {
            if(!data || !data.length) {
                console.log("playback_error:data transform error!");
                return;
            }
            var datas = [];
            for(var i = 0, len = data.length; i < len; i++) {
                var ph = data[i].num;
                var dataobj = {};
                dataobj.timePosList = [];
                for(var j = 0, lenj = data[i].posList.length; j < lenj; j++) {
                    var obj = {};
                    var pj = data[i].posList[j];
                    obj.lng = pj.lo / 600000; // 经度 【必须参数】
                    obj.lat = pj.la / 600000; // 纬度 【必须参数】
                    obj.time = pj.ti; //以秒为单位的unix时间戳 【必须参数】
                    obj.dir = parseFloat(pj.co / 10);
                    obj.heading = parseFloat(pj.he);
                    obj.speed = parseFloat(pj.sp / 10);
                    obj.info = [
                        { key: '批号', value: ph },
                        { key: '经度', value: L.ict.app.util.tool.latlngTodfmStr(obj.lng, 'lng') },
                        { key: '纬度', value: L.ict.app.util.tool.latlngTodfmStr(obj.lat, 'lat') },
                        { key: '时间', value: L.PlayBack.Util.getTimeStrFromUnix(pj.ti, 's') },
                        { key: '航向', value: (pj.co / 10).toFixed(1) + '°' },
                        { key: '船艏向', value: parseFloat(pj.he).toFixed(1) + '°' },
                        { key: '航速', value: parseFloat(pj.sp / 10).toFixed(1) + '节' },
                    ];
                    dataobj.timePosList.push(obj);
                }
                datas.push(dataobj);
            }
            return datas;
        }
    });

});